package com.coolw.spring.statemachine.support;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 在内存中持久化状态机
 *
 * @author coolw
 * @date 2024/4/18 11:46
 */
@Slf4j
@Component
public class MemoryStateMachinePersist<S extends BaseState, E extends BaseEvent> implements StateMachinePersist<S, E, String> {

    private final Map<String, StateMachineContext<S, E>> persistMap = new HashMap<>();

    @Override
    public void write(StateMachineContext<S, E> context, String contextObj) throws Exception {
        log.info("持久化状态机,context:{},contextObj:{}", JSON.toJSONString(context), contextObj);
        persistMap.put(contextObj, context);
    }

    @Override
    public StateMachineContext<S, E> read(String contextObj) throws Exception {
        StateMachineContext<S, E> stateMachineContext = persistMap.get(contextObj);
        log.info("获取状态机,contextObj:{},stateMachineContext:{}", contextObj, JSON.toJSONString(stateMachineContext));
        return stateMachineContext;
    }
}
